<?php

class Model_Charge extends Model_Common {
    private $resHandler = null;
    private $reqHandler = null;
    private $pay = null;
	/* 订单号 */
	public function getOrderId($changeid,$orderinfo) {
		if($changeid) {
            $charge = DI()->notorm->charge_rules->select('*')->where('id=?', $changeid)->fetchOne();

           /* if (!$charge || $charge['coin'] != $orderinfo['coin'] || ($charge['money'] != $orderinfo['money'] && $charge['money'] != $orderinfo['money_ios'])) {
                return 1003;
            }*/

            $orderinfo['coin_give'] = $charge['give'];
        }

		$result= DI()->notorm->users_charge->insert($orderinfo);
		//$money=$charge['money']*100;
        //$img_url=$this->submitOrderInfo($orderinfo['orderno'],$money,$pay_account);
		return $result;
	}

    /**
     * 会员卡充值规则
     */
	public function  monthCardList(){
        $charge=DI()->notorm->month_card->select('*')->order("orderno asc")->fetchAll();
        return $charge;
    }

    /* 订单号 */
    public function getCardOrderId($changeid,$orderinfo) {
        if($changeid) {
            $charge = DI()->notorm->month_card->select('*')->where('id=?', $changeid)->fetchOne();

            if (!$charge  || ($charge['coin'] != $orderinfo['money'] )) {
                return 1003;
            }
            $orderinfo['effect'] = "充值会员".$charge['name'];
            $orderinfo['month'] =$charge['month'];
        }

        $result= DI()->notorm->users_charge->insert($orderinfo);

        return $result;
    }

    /**
     * 播豆支付
     */
    public  function  getcoinCard($uid,$changeid)
    {
        $charge = DI()->notorm->month_card->select('*')->where('id=?', $changeid)->fetchOne();
        $user = DI()->notorm->users->where('id=?', $uid)->fetchOne();
        if (($charge['coin'] > $user['coin'])) {
            return 1001;
        }

        $flag = DI()->notorm->users->where('id=?', $uid)
            ->update( array('coin' => new NotORM_Literal("coin - {$charge['coin']}")));
        $manager=DI()->notorm->users->where('invitation_code=?', $user['inviter'])->fetchOne();
        if($manager){ //区域经理提成
            $configpri=$this->getConfigPri();

            $ticheng=$charge['coin']*$configpri['manager_rate']/100;
            /* 更新用户余额 消费 */
            $isuid =DI()->notorm->users
                ->where('id = ?', $manager['id'])
                ->update(array('votes' => new NotORM_Literal("votes + {$ticheng}"), 'votestotal' => new NotORM_Literal("votestotal + {$ticheng}")));
            $insert2=array("type"=>'income',"action"=>'manager_card',"uid"=> $manager['id'],"touid"=> $manager['id'],"giftid"=>0,"giftcount"=>0,"totalcoin"=>$ticheng,"showid"=>time(),"addtime"=>time() );
            $isup=DI()->notorm->users_coinrecord->insert($insert2);
        }

        /* 添加消费记录 */
        DI()->notorm->users_coinrecord
            ->insert(array("type"=>'expend',"action"=>'card',"uid"=>$uid,"touid"=>$uid,"giftid"=>0,"giftcount"=>0,"totalcoin"=>$charge['coin'],"showid"=>$charge['month'],"addtime"=>time() ));
        $nowtime=time();
        if($user['member_validity']){
            if($nowtime>$user['member_validity']){
                $efftime =strtotime('+'.$charge['month'].'month');
            }else{
                $efftime =strtotime('+'.$charge['month'].' month',$user['member_validity']);
            }

        }else{
            $efftime =strtotime('+'.$charge['month'].'month');
        }
        //$efftime =strtotime('+'.$charge['month'].'month');
        $where['member_validity']=$efftime;

        $user_flag = DI()->notorm->users->where('id=?',$uid)->update($where);

        return 0;
    }

    /**
     * 提交订单信息
     */
    public function submitOrderInfo($orderid,$money){
        $this->resHandler = new ClientResponseHandler();
        $this->reqHandler = new RequestHandler();
        $this->pay = new PayHttpClient();

        $configpri=$this->getConfigPri();

        $this->reqHandler->setGateUrl('https://pay.swiftpass.cn/pay/gateway');
        $this->reqHandler->setKey($configpri['aliapp_key_android']);


        $this->reqHandler->setParameter('service','pay.alipay.native');//接口类型
        $this->reqHandler->setParameter('mch_id',$configpri['aliapp_partner']);//必填项，商户号，由平台分配
        $this->reqHandler->setParameter('notify_url','http://zb.xy77.cn/index.php/appapi/notify/aliPay');
        $this->reqHandler->setParameter('version','2.0');
        $this->reqHandler->setParameter('out_trade_no',$orderid);
        $this->reqHandler->setParameter('body','充值');
        $this->reqHandler->setParameter('total_fee',$money);
        $this->reqHandler->setParameter('mch_create_ip','127.0.0.1');

        $this->reqHandler->setParameter('nonce_str',mt_rand(time(),time()+rand()));//随机字符串，必填项，不长于 32 位
        $this->reqHandler->createSign();//创建签名

        $data = Utils::toXml($this->reqHandler->getAllParameters());
        //var_dump($data);

        $this->pay->setReqContent($this->reqHandler->getGateURL(),$data);
        if($this->pay->call()){
            $this->resHandler->setContent($this->pay->getResContent());
            $this->resHandler->setKey($this->reqHandler->getKey());
            if($this->resHandler->isTenpaySign()){
                //当返回状态与业务结果都为0时才返回支付二维码，其它结果请查看接口文档
                if($this->resHandler->getParameter('status') == 0 && $this->resHandler->getParameter('result_code') == 0){
                    return $this->resHandler->getParameter('code_img_url');
                   // echo json_encode(array('code_img_url'=>$this->resHandler->getParameter('code_img_url'),
                    //    'code_url'=>$this->resHandler->getParameter('code_url')));
                    exit();
                }else{
                   // echo json_encode(array('status'=>500,'msg'=>'Error Code:'.$this->resHandler->getParameter('err_code').' Error Message:'.$this->resHandler->getParameter('err_msg')));
                    exit();
                }
            }
           // echo json_encode(array('status'=>500,'msg'=>'Error Code:'.$this->resHandler->getParameter('status').' Error Message:'.$this->resHandler->getParameter('message')));
        }else{
           // echo json_encode(array('status'=>500,'msg'=>'Response Code:'.$this->pay->getResponseCode().' Error Info:'.$this->pay->getErrInfo()));
        }
        }

    /**
     *微信
     * @param $orderid
     * @param $money
     * @return int|string
     */
        public function  qrcodepay($orderid,$money){
            $this->resHandler = new ClientResponseHandler();
            $this->reqHandler = new RequestHandler();
            $this->pay = new PayHttpClient();

            $configpri=$this->getConfigPri();
            $this->reqHandler->setGateUrl("https://pay.swiftpass.cn/pay/gateway");
            $this->reqHandler->setKey($configpri['wx_key']);

            $this->reqHandler->setParameter('out_trade_no',$orderid);
            $this->reqHandler->setParameter('total_fee',$money);

            $this->reqHandler->setParameter('service','pay.weixin.native');//接口类型
            $this->reqHandler->setParameter('mch_id',$configpri['wx_mchid']);//必填项，商户号，由平台分配
            $this->reqHandler->setParameter('version','2.0');
            $this->reqHandler->setParameter('op_shop_id','1314');
            $this->reqHandler->setParameter('device_info','长江');

            $this->reqHandler->setParameter('body','充值');

            $this->reqHandler->setParameter('mch_create_ip','127.0.0.1');

            //$this->reqHandler->setParameter('out_trade_no',mt_rand(time(),time()+rand()));

            $this->reqHandler->setParameter('op_device_id','东风一号');
            $this->reqHandler->setParameter('limit_credit_pay','1');
            //this->reqHandler->setParameter('goods_tag','1fds');
            //$this->reqHandler->setParameter('groupno','8111100093');
            //通知地址，必填项，接收平台通知的URL，需给绝对路径，255字符内格式如:http://wap.tenpay.com/tenpay.asp
            //$notify_url = 'http://'.$_SERVER['HTTP_HOST'];
            //$this->reqHandler->setParameter('notify_url',$notify_url.'/payInterface/request.php?method=callback');
            $this->reqHandler->setParameter('notify_url',"http://zb.xy77.cn/index.php/appapi/notify/callback");
            $this->reqHandler->setParameter('nonce_str',mt_rand(time(),time()+rand()));//随机字符串，必填项，不长于 32 位
            $this->reqHandler->createSign();//创建签名

            $data = Utils::toXml($this->reqHandler->getAllParameters());
            //var_dump($data);

            $this->pay->setReqContent($this->reqHandler->getGateURL(),$data);
            if($this->pay->call()){
                $this->resHandler->setContent($this->pay->getResContent());
                $this->resHandler->setKey($this->reqHandler->getKey());
                if($this->resHandler->isTenpaySign()){
                    //当返回状态与业务结果都为0时才返回支付二维码，其它结果请查看接口文档
                    if($this->resHandler->getParameter('status') == 0 && $this->resHandler->getParameter('result_code') == 0){
                        return $this->resHandler->getParameter('code_img_url');
                       // echo json_encode(array('code_img_url'=>$this->resHandler->getParameter('code_img_url'),
                         //   'code_url'=>$this->resHandler->getParameter('code_url'),
                           // 'code_status'=>$this->resHandler->getParameter('code_status')));
                        return 1001;
                        exit();
                    }else{
                      //  echo json_encode(array('status'=>500,'msg'=>'Error Code:'.$this->resHandler->getParameter('err_code').' Error Message:'.$this->resHandler->getParameter('err_msg')));
                        return 1001;
                        exit();
                    }
                }
                //echo json_encode(array('status'=>500,'msg'=>'Error Code:'.$this->resHandler->getParameter('status').' Error Message:'.$this->resHandler->getParameter('message')));
            }else{
                //echo json_encode(array('status'=>500,'msg'=>'Response Code:'.$this->pay->getResponseCode().' Error Info:'.$this->pay->getErrInfo()));
            }
        }
}
